package com.currency.mall.ui.my.recharge;

import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.content.ContextCompat;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.currency.mall.Constant;
import com.currency.mall.R;
import com.currency.mall.entity.RechargeBean;
import com.currency.mall.entity.RechargeRecordBean;
import com.currency.mall.entity.UserAccoutBean;
import com.currency.mall.netWork.NetWork;
import com.currency.mall.util.Util;
import com.currency.mall.widget.MyRadioGroup;
import com.mifengs.commonbase.base.BaseActivity;
import com.mifengs.commonbase.util.StatusBarCompat;
import com.mifengs.commonbase.util.StatusBarUtils;
import com.mifengs.commonbase.util.ToastUitl;

import java.util.HashMap;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import rx.Observer;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

/**
 * Created by Administrator on 2018/12/25.
 */

public class RechargeActivity extends BaseActivity {

    @BindView(R.id.ll_back)
    LinearLayout llBack;
    @BindView(R.id.tv_title)
    TextView tvTitle;
    @BindView(R.id.rl_tile)
    RelativeLayout rlTile;
    @BindView(R.id.account_balance_text)
    TextView accountBalanceText;
    @BindView(R.id.tv_account_balance)
    TextView tvAccountBalance;
    @BindView(R.id.tv_account_available_balance)
    TextView tvAccountAvailableBalance;
    @BindView(R.id.tv_principal)
    TextView tvPrincipal;
    @BindView(R.id.tv_company)
    TextView tvCompany;
    @BindView(R.id.et_input_recharge_price)
    EditText etInputRechargePrice;
    @BindView(R.id.tv_recommend)
    TextView tvRecommend;
    @BindView(R.id.rb_1)
    RadioButton rb1;
    @BindView(R.id.rb_2)
    RadioButton rb2;
    @BindView(R.id.rb_5)
    RadioButton rb5;
    @BindView(R.id.rb_10)
    RadioButton rb10;
    @BindView(R.id.rb_20)
    RadioButton rb20;
    @BindView(R.id.rb_50)
    RadioButton rb50;
    @BindView(R.id.radioGroup)
    MyRadioGroup radioGroup;
    @BindView(R.id.btn_recharge)
    Button btnRecharge;
    private int principal = 50000;
    private Dialog waitPayDialogShow, cancelOrderDialog;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_recharge);
        ButterKnife.bind(this);
        StatusBarCompat.setStatusBarColor(this, ContextCompat.getColor(getContext(), R.color.title_color));
        StatusBarUtils.StatusBarLightMode(this);
        init();
    }

    private void init() {
        etInputRechargePrice.setText(principal + "");
        etInputRechargePrice.addTextChangedListener(textWatcher);
        etInputRechargePrice.setSelection(etInputRechargePrice.getText().toString().length());
        getUserAccount();
        radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                switch (checkedId) {
                    case R.id.rb_1:
                        principal = 10000;
                        break;
                    case R.id.rb_2:
                        principal = 20000;
                        break;
                    case R.id.rb_5:
                        principal = 50000;
                        break;
                    case R.id.rb_10:
                        principal = 100000;
                        break;
                    case R.id.rb_20:
                        principal = 200000;
                        break;
                    case R.id.rb_50:
                        principal = 500000;
                        break;
                }
                etInputRechargePrice.setText(principal + "");
                etInputRechargePrice.setSelection(etInputRechargePrice.getText().toString().length());

            }
        });
        getRechargeData();

    }

    TextWatcher textWatcher = new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            String phone = etInputRechargePrice.getText().toString().trim();
            if (TextUtils.isEmpty(phone) || TextUtils.isEmpty(s)) {
                btnRecharge.setBackgroundResource(R.drawable.btn_bg);
                btnRecharge.getBackground().setAlpha(50);
                btnRecharge.setClickable(false);
            } else {
                btnRecharge.setBackgroundResource(R.drawable.btn_bg);
                btnRecharge.getBackground().setAlpha(250);
                btnRecharge.setClickable(true);

            }
        }

        @Override
        public void afterTextChanged(Editable s) {
            if (!"".equals(etInputRechargePrice.getText().toString())) {
                principal = Integer.parseInt(etInputRechargePrice.getText().toString());
                if (!getRadioButtonChecked(principal)) {
                    setRadioButtonChecked();
                }
            }

        }
    };

    private boolean getRadioButtonChecked(int principal) {
        if (principal == 10000) {
            return true;
        } else if (principal == 20000) {
            return true;
        } else if (principal == 50000) {
            return true;
        } else if (principal == 100000) {
            return true;
        } else if (principal == 200000) {
            return true;
        } else if (principal == 500000) {
            return true;
        }
        return false;
    }

    private void setRadioButtonChecked() {
        rb1.setChecked(false);
        rb2.setChecked(false);
        rb5.setChecked(false);
        rb10.setChecked(false);
        rb20.setChecked(false);
        rb50.setChecked(false);
    }

    public void getUserAccount() {
        NetWork.getUserApi().accountQuery()
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<UserAccoutBean>() {
                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onError(Throwable e) {
                    }

                    @Override
                    public void onNext(UserAccoutBean userAccoutBean) {
                        if (userAccoutBean.getCode().equals(Constant.SUCCESS_CODE)) {
                            tvAccountBalance.setText(Util.formatTosepara(Double.parseDouble(userAccoutBean.getUserAccount().getTotalSum())));
                            tvAccountAvailableBalance.setText("可用" + Util.formatTosepara(Double.parseDouble(userAccoutBean.getUserAccount().getUsabSum())) + " ，" + "冻结" + Util.formatTosepara(Double.parseDouble(userAccoutBean.getUserAccount().getFreezeSum())));
                        } else {
                            ToastUitl.show(userAccoutBean.getMsg(), 200);
                        }
                    }
                });
    }

    private void toRechargeIntent(RechargeBean rechargeBean) {
        Intent intent = new Intent(getContext(), RechargeDetailsActivity.class);
        intent.putExtra("type", 0);
        intent.putExtra("timeOut", rechargeBean.getTimeOut());
        intent.putExtra("bankInfo", rechargeBean.getBankInfo());
        intent.putExtra("rechargeInfo", rechargeBean.getRecharge());
        intent.putExtra("alipayInfo", rechargeBean.getAlipayInfo());
        intent.putExtra("price", etInputRechargePrice.getText().toString());
        startActivity(intent);
        finish();

    }

    private void waitPayDialogShow() {
        waitPayDialogShow = new Dialog(getContext(), R.style.dialog);
        waitPayDialogShow.setContentView(R.layout.dialog_not_title);
        waitPayDialogShow.show();
        TextView tvInfo = (TextView) waitPayDialogShow.findViewById(R.id.tv_info);
        tvInfo.setText("您有未完成的充值订单");
        Button okBtn = waitPayDialogShow.findViewById(R.id.bt_ok);
        okBtn.setText("去查看");
        okBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                waitPayDialogShow.dismiss();
                toRechargeStatus();
            }
        });
        Button cancleBtn = waitPayDialogShow.findViewById(R.id.bt_cancle);
        cancleBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                waitPayDialogShow.dismiss();
            }
        });
    }


    private void toRechargeStatus() {
        startActivity(new Intent(getContext(), RechargeRecordActivity.class));
    }

    /**
     * 等待付款
     *
     * @param
     */
    public void getRechargeData() {
        HashMap<String, Object> hashMap = new HashMap<>();
        hashMap.put("status", "PAY_WAIT");
        hashMap.put("pageNum", 1);
        hashMap.put("pageSize", 100);
        NetWork.getOderApi().rechargeOrder(hashMap)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<RechargeRecordBean>() {
                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onError(Throwable e) {
                    }

                    @Override
                    public void onNext(RechargeRecordBean rechargeRecordBean) {
                        if (rechargeRecordBean.getCode().equals(Constant.SUCCESS_CODE)) {
                            if (rechargeRecordBean.getPageList().getList().size() > 0)
                                waitPayDialogShow();
                        } else {
                            ToastUitl.show(rechargeRecordBean.getMsg(), 200);
                        }

                    }
                });
    }

    public void recharge(String money) {
        HashMap<String, Object> hashMap = new HashMap<>();
        hashMap.put("money", money);
        hashMap.put("payType", "BANK");
        showLoading();
        NetWork.getUserApi().rechargeCreate(hashMap)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<RechargeBean>() {
                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onError(Throwable e) {
                        hideLoading();
                    }

                    @Override
                    public void onNext(RechargeBean rechargeBean) {
                        hideLoading();
                        if (rechargeBean.getCode().equals(Constant.SUCCESS_CODE)) {
                            ToastUitl.show("充值订单成功，请付款", 200);
                            toRechargeIntent(rechargeBean);
                        } else {
                            ToastUitl.show(rechargeBean.getMsg(), 200);
                        }
                    }
                });
    }

    @OnClick({R.id.ll_back, R.id.btn_recharge, R.id.ll_recharge_record})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.ll_back:
                finish();
                break;
            case R.id.btn_recharge:
                if (Integer.parseInt(etInputRechargePrice.getText().toString()) >= 100) {
                    recharge(etInputRechargePrice.getText().toString());
                } else {
                    ToastUitl.show("最小充值数额100元", 200);
                }
                break;
            case R.id.ll_recharge_record:
                startActivity(new Intent(getContext(), RechargeRecordActivity.class));
                break;
        }
    }
}
